#define _CRT_SECURE_NO_WARNINGS
#include"Tree.h"

BTNode* buyNode(BTDataType x)
{
	BTNode* new = (BTNode*)malloc(sizeof(BTNode));
	if (!new)
	{
		perror("malloc");
		exit(1);
	}
	new->data = x;
	new->left = new->right = NULL;
	return new;
}

void BinaryTreeDestory(BTNode** root)
{
	assert(root);
	if (!*root)
		return;
	BinaryTreeDestory(&(*root)->left);
	BinaryTreeDestory(&(*root)->right);
	free(*root);
	*root = NULL;
}

void BinaryTreePrevOrder(BTNode* root)
{
	if (!root)
		return;
	printf("%d ", root->data);
	BinaryTreePrevOrder(root->left);
	BinaryTreePrevOrder(root->right);
}

void BinaryTreePostOrder(BTNode* root)
{
	assert(root);
	BinaryTreePrevOrder(root->left);
	BinaryTreePrevOrder(root->right);
	printf("%d ", root->data);
}

void BinaryTreeInOrder(BTNode* root)
{
	assert(root);
	BinaryTreePrevOrder(root->left);
	printf("%d ", root->data);
	BinaryTreePrevOrder(root->right);
}

int BinaryTreeSize(BTNode* root)
{
	if (!root)
		return 0;
	return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}

int BinaryTreeLeafSize(BTNode* root)
{
	if (!root)
		return 0;
	if (root->left == NULL && root->right == NULL)
		return 1;
	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
}

int BinaryTreeLevelKSize(BTNode* root, int k)
{
	if (!root)
		return 0;
	if (k == 1)
		return 1;
	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}

BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
	if (!root)
		return NULL;
	if (root->data == x)
		return root;
	BTNode* leftfind = BinaryTreeFind(root->left,x);
	if (leftfind)
		return leftfind;
	BTNode* rightfind = BinaryTreeFind(root->right,x);
	if (rightfind)
		return rightfind;
	return NULL;
}

void BinaryTreeLevelOrder(BTNode* root)
{
	if (!root)
		printf("null\n");
	Queue qu;
	QueueInit(&qu);
	QueuePush(&qu,  root);
	while (!QueueEmpty(&qu))
	{
		BTNode* tmp = QueueFront(&qu);
		QueuePop(&qu);
		printf("%d ", tmp->data);
		if (tmp->left)
			QueuePush(&qu, tmp->left);
		if (tmp->right)
			QueuePush(&qu, tmp->right);
	}
	QueueDestroy(&qu);
	printf("\n");
}

int BinaryTreeComplete(BTNode* root)
{
	assert(root);
	Queue qu;
	QueueInit(&qu);
	QueuePush(&qu, root);
	while (!QueueEmpty(&qu))
	{
		BTNode* tmp = QueueFront(&qu);
		if (!tmp)
			break;
		QueuePop(&qu);
		QueuePush(&qu, tmp->left);
		QueuePush(&qu, tmp->right);
	}
	while (!QueueEmpty(&qu))
	{
		if (QueueFront(&qu))
			return false;
		QueuePop(&qu);
	}
	return true;
	QueueDestroy(&qu);
}